<?php

namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\HttpCurl;

class XingTuBot
{
    use HttpCurl;

    /* @var $httpClient HttpClient */
    private $httpClient = null;

    public function __construct()
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function getHeader()
    {
        return [
            'Cookie' => 'tt_webid=7398447968917784115; is_staff_user=false; Hm_lvt_5d77c979053345c4bd8db63329f818ec=1728102171; HMACCOUNT=084530B57407D94A; csrf_session_id=1df625f77ff0845ae25fc4e0d8c86411; passport_csrf_token=c5fa71e87e4e6af345c1ab762558ee8d; passport_csrf_token_default=c5fa71e87e4e6af345c1ab762558ee8d; csrftoken=BtrRdxYkYW3jOBZjwqKdsBA3RMh8v9wX; star_login_type=mcn_oceanengine; s_v_web_id=verify_m1vqgxxr_252b08a4_4652_0bb7_db18_5e8815afc90b; Hm_lpvt_5d77c979053345c4bd8db63329f818ec=1728107316; passport_auth_status=788cbab6c72793be38cbfe6c9bc1b95e%2C7dad9c6f13493a2bcd6b008c87e70973; passport_auth_status_ss=788cbab6c72793be38cbfe6c9bc1b95e%2C7dad9c6f13493a2bcd6b008c87e70973; uid_tt=ae213817823aefe95195b2d0f69d88c5; uid_tt_ss=ae213817823aefe95195b2d0f69d88c5; sid_tt=a0ea952d8105e2de7a4117bc3ce23455; sessionid=a0ea952d8105e2de7a4117bc3ce23455; sessionid_ss=a0ea952d8105e2de7a4117bc3ce23455; auth_token=c94b923011e84bb69bc10d051a57273a; auth_token_ss=c94b923011e84bb69bc10d051a57273a; tt_scid=aDEkXT5Ylq7jnJJFrHaZYbeCiYhJ5D4xitDFxP70TcuVdPoQN4-JAqqYS6nv3QEe7052; sid_guard=a0ea952d8105e2de7a4117bc3ce23455%7C1728112654%7C5184000%7CWed%2C+04-Dec-2024+07%3A17%3A34+GMT; sid_ucp_v1=1.0.0-KDFhYzAxMzYyNjk2YjMxZTJhNjA3MjM0YTFlNTRkODgxYTk2ZTVlZDcKFwjOvuC76PT1BxCO0IO4BhimDDgCQPEHGgJsZiIgYTBlYTk1MmQ4MTA1ZTJkZTdhNDExN2JjM2NlMjM0NTU; ssid_ucp_v1=1.0.0-KDFhYzAxMzYyNjk2YjMxZTJhNjA3MjM0YTFlNTRkODgxYTk2ZTVlZDcKFwjOvuC76PT1BxCO0IO4BhimDDgCQPEHGgJsZiIgYTBlYTk1MmQ4MTA1ZTJkZTdhNDExN2JjM2NlMjM0NTU; star_sessionid=a0ea952d8105e2de7a4117bc3ce23455; possess_scene_star_id=1801820033071123'];
    }

    public function sign($params)
    {

        $str = "limit{$params['limit']}order_by{$params['order_by']}page{$params['page']}service_method{$params['service_method']}service_name{$params['service_name']}sign_strict{$params['sign_strict']}";
        $key = 'e9fefef711becf4c3d7bfef829578b0c';

        return md5($str . $key);
    }

    public function taskDetail($taskId)
    {
        $url = 'https://www.xingtu.cn/gw/api/challenge/mcn_get_challenge?';
        $body = [
            "challenge_id" => $taskId,
        ];
        $response = $this->httpClient->sendGetRequest($url . http_build_query($body), $body, $this->getHeader());


        $result = json_decode($response->getBody()->getContents(), true);

        if (isset($result['base_resp']['status_code']) && in_array($result['base_resp']['status_code'], [0])) {
            return $result;
        }

        return false;
    }

    public function getJoinTasks($page, $limit, $keyword = "")
    {
        $url = "https://www.xingtu.cn/gw/api/challenge/mcn_get_contracted_challenge_list?";
        $body = [
            "limit"=>$limit,
            "page"=>$page,
        ];
        if (!empty($keyword)) {
            $body['keyword'] = $keyword;
        }
//        $body['sign'] = $this->sign($body);

        $response = $this->httpClient->sendGetRequest($url . http_build_query($body), $body, $this->getHeader());

        $result = json_decode($response->getBody()->getContents(), true);
        if (isset($result['demand_info_list'])) {
            return $result['demand_info_list'];
        }

        return [];
    }

    public function joinTask($taskId, $rate = 100) {
        $url = "https://www.xingtu.cn/gw/api/challenge/mcn_contract_challenge?";

        $body = [
            "challenge_id" => $taskId,
            "mcn_profit_rate"=> $rate * 10
        ];

        $response = $this->httpClient->sendGetRequest($url . http_build_query($body), $body, $this->getHeader());

        $result = json_decode($response->getBody()->getContents(), true);

        if (isset($result['base_resp']['status_code']) && in_array($result['base_resp']['status_code'], [0, 1])) {
            return true;
        }

        return false;
    }

    public function getPublicTasks($page, $keyword = "",  $limit = 100)
    {
        $url = "https://www.xingtu.cn/h/api/gateway/handler_get/?";
        $body = [
            "page"=>$page,
            "limit"=>$limit,
            "order_by"=>"expiration_time_end",
            "search_origin" => 7,
            "mission_search_tag" => 0,
            "service_name" => "challenge.AdStarChallengeService",
            "service_method" => "McnGetContractChallengeList",
            "sign_strict" => 1
        ];
        if (!empty($body['keyword'])) {
            $body['keyword'] = $keyword;
        }
        $body['sign'] = $this->sign($body);

       $response = $this->httpClient->sendGetRequest($url . http_build_query($body), $body, $this->getHeader());

        $result = json_decode($response->getBody()->getContents(), true);

        if (isset($result['data']['demand_info_list'])) {
            return $result['data']['demand_info_list'];
        }

        return [];
    }

    public function createQrcode($uid, $taskId)
    {
        $url = 'https://www.xingtu.cn/gw/api/challenge/mcn_create_or_update_qr_code';
        $body = [
            "task_id"=>$taskId,
            "code_info"=>['name' => $uid],
        ];

        $header = $this->getHeader();
        $cookies = explode('; ', $header['Cookie']);

        foreach($cookies as $cookie) {
            $keyAndValue = explode('=', $cookie);
            $allCookies[$keyAndValue[0]] = $keyAndValue[1];
        }

        $header['Content_Type'] = 'application/json';
        $header['X-Csrftoken'] = $allCookies['csrftoken'] ?? "";
        $header['X-Login-Source'] = 1;

        $response = $this->httpClient->sendPostRequest($url, $body, $header);
        $result = json_decode($response->getBody()->getContents(), true);
        var_dump($result, $header);
        if (isset($result['code_info']['id'])) {
            return $result['code_info']['id'];
        }

        return false;
    }
}